<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="年份" prop="year">
              <el-date-picker
                v-model="queryParams.year"
                type="year"
                placeholder="请选择年份"
                value-format="YYYY"
                @change="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never" >
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Search" @click="handleAdd" v-hasPermi="['basicPublic:populationBase:query']">查询</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="computedFocusNum" @selection-change="handleSelectionChange" height="65vh">
        <el-table-column label="主键ID" align="center" prop="id" v-if="false" />
        <el-table-column label="机构编码" align="center" prop="deptCategory" fixed/>
        <el-table-column label="机构名称" align="center" prop="deptName" width="180px" fixed/>
        <el-table-column label="年份" align="center" prop="year" />
        <el-table-column label="常住人口数" align="center" prop="residentPopulationNum" />
        <el-table-column label="普通人群数" align="center" prop="generalPopulationNum" />
        <el-table-column label="重点人口数" align="center" prop="focusNum" />
        <el-table-column label="孕产数" align="center" prop="liveBirthNum" />
        <el-table-column label="0~6岁儿童数" align="center" prop="zeroNum" />
        <el-table-column label="3岁以下儿童数" align="center" prop="threeNum" />
        <el-table-column label="35岁以上" align="center" prop="thirtyFiveNum" />
        <el-table-column label="65岁以上" align="center" prop="sixtyFiveNum" />
        <el-table-column label="高血压任务数" align="center" prop="hypertensionNum" />
        <el-table-column label="糖尿病任务数" align="center" prop="diabetesNum" />
        <el-table-column label="肺结核任务数" align="center" prop="tuberculosisNum" />
        <el-table-column label="慢阻肺" align="center" prop="copdNum" />
        <el-table-column label="严重精神障碍任务数" align="center" prop="psychosisNum" />
        <el-table-column label="老年人肺结核筛查任务数" align="center" prop="tuberCheckNum" />
        <el-table-column label="残疾人人数" align="center" prop="disabledPersonsNum" />
        <el-table-column label="计生扶持" align="center" prop="specialHelpNum" />
        <el-table-column label="乡村振兴检测对象数" align="center" prop="ruralRevitalizationObjNum" />
        <el-table-column label="孕产妇数" align="center" prop="pregnantWomanNum" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['basicPublic:populationBase:edit']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改人口基数对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="populationBaseFormRef" :model="form" :rules="rules">
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="所属机构" prop="deptName">
              <el-input v-model="form.deptName" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年份" prop="year">
              <el-input v-model="form.year" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="常住人口数" prop="residentPopulationNum">
              <el-input v-model.number="form.residentPopulationNum" placeholder="请输入常住人口数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="普通人群数" prop="generalPopulationNum">
              <el-input v-model.number="form.generalPopulationNum" placeholder="请输入普通人群数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="重点人口数" prop="computedFocusNum">
                <el-input :value="computedFocusNum" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="孕产数" prop="liveBirthNum">
              <el-input v-model="form.liveBirthNum" placeholder="请输入活产数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="0~6岁儿童数" prop="zeroNum">
              <el-input v-model="form.zeroNum" placeholder="请输入0~6岁儿童数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="3岁以下儿童数" prop="threeNum">
              <el-input v-model="form.threeNum" placeholder="请输入3岁以下儿童数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="35岁以上" prop="thirtyFiveNum">
              <el-input v-model="form.thirtyFiveNum" placeholder="请输入35岁以上" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="65岁以上" prop="sixtyFiveNum">
              <el-input v-model="form.sixtyFiveNum" placeholder="请输入65岁以上" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="高血压任务数" prop="hypertensionNum">
              <el-input v-model="form.hypertensionNum" placeholder="请输入高血压任务数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="糖尿病任务数" prop="diabetesNum">
              <el-input v-model="form.diabetesNum" placeholder="请输入糖尿病任务数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="肺结核任务数" prop="tuberculosisNum">
              <el-input v-model="form.tuberculosisNum" placeholder="请输入肺结核任务数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="慢阻肺" prop="copdNum">
              <el-input v-model="form.copdNum" placeholder="请输入慢阻肺" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="严重精神障碍任务数" prop="psychosisNum">
              <el-input v-model="form.psychosisNum" placeholder="请输入严重精神障碍任务数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="老年人肺结核筛查任务数" prop="tuberCheckNum">
              <el-input v-model="form.tuberCheckNum" placeholder="请输入老年人肺结核筛查任务数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="残疾人人数" prop="disabledPersonsNum">
              <el-input v-model="form.disabledPersonsNum" placeholder="请输入残疾人人数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计生扶持" prop="specialHelpNum">
              <el-input v-model="form.specialHelpNum" placeholder="请输入计生扶持" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="乡村振兴检测对象数" prop="ruralRevitalizationObjNum">
              <el-input v-model="form.ruralRevitalizationObjNum" placeholder="请输入乡村振兴检测对象数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="孕产妇数" prop="pregnantWomanNum">
              <el-input v-model="form.pregnantWomanNum" placeholder="请输入孕产妇数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">

          </el-col>
        </el-row>


        <!--<el-form-item label="生效开始日期" prop="effectiveStartDate">-->
        <!--  <el-date-picker clearable-->
        <!--    v-model="form.effectiveStartDate"-->
        <!--    type="datetime"-->
        <!--    value-format="YYYY-MM-DD HH:mm:ss"-->
        <!--    placeholder="请选择生效开始日期">-->
        <!--  </el-date-picker>-->
        <!--</el-form-item>-->
        <!--<el-form-item label="生效结束日期" prop="effectiveEndDate">-->
        <!--  <el-date-picker clearable-->
        <!--    v-model="form.effectiveEndDate"-->
        <!--    type="datetime"-->
        <!--    value-format="YYYY-MM-DD HH:mm:ss"-->
        <!--    placeholder="请选择生效结束日期">-->
        <!--  </el-date-picker>-->
        <!--</el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PopulationBase" lang="ts">
import { listPopulationBase, getPopulationBase, delPopulationBase, addPopulationBase, updatePopulationBase } from '@/api/basicPublic/populationBase';
import { PopulationBaseVO, PopulationBaseQuery, PopulationBaseForm } from '@/api/basicPublic/populationBase/types';
import {parseTime} from "../../../utils/ruoyi";
import { getCurrentInstance, ComponentInternalInstance } from 'vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const populationBaseList = ref<PopulationBaseVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const populationBaseFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: PopulationBaseForm = {
  id: undefined,
  deptId: undefined,
  year: undefined,
  residentPopulationNum: 0,
  generalPopulationNum: 0,
  liveBirthNum: undefined,
  zeroNum: undefined,
  threeNum: undefined,
  thirtyFiveNum: undefined,
  sixtyFiveNum: undefined,
  hypertensionNum: undefined,
  diabetesNum: undefined,
  tuberculosisNum: undefined,
  copdNum: undefined,
  psychosisNum: undefined,
  tuberCheckNum: undefined,
  disabledPersonsNum: undefined,
  specialHelpNum: undefined,
  ruralRevitalizationObjNum: undefined,
  pregnantWomanNum: undefined,
  effectiveStartDate: undefined,
  effectiveEndDate: undefined,
}
const data = reactive<PageData<PopulationBaseForm, PopulationBaseQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: undefined,
    year: undefined,
    params: {
    },
  },
  rules: {
    id: [
      { required: true, message: "主键ID不能为空", trigger: "blur" }
    ],
    deptId: [
      { required: true, message: "部门ID不能为空", trigger: "blur" }
    ],
    year: [
      { required: true, message: "年份不能为空", trigger: "blur" }
    ],
    residentPopulationNum: [
      { required: true, message: "请输入常住人口数", trigger: "blur" },
    ],
    generalPopulationNum: [
      { required: true, message: "请输入普通人群数", trigger: "blur" },
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

// 获取当前年份
queryParams.value.year = new Date().getFullYear().toString();

/** 查询人口基数列表 */
const getList = async () => {
  loading.value = true;
  const res = await listPopulationBase(queryParams.value);
  populationBaseList.value = res.data;
  loading.value = false;
};
//计算属性：计算重点人口数
const computedFocusNums = computed(() => {
  if (form.value.residentPopulationNum !== null && form.value.generalPopulationNum !== null) {
    return form.value.residentPopulationNum - form.value.generalPopulationNum;
  }
  return 0;
});

// 计算属性：处理整个 populationBaseList 数组并添加 focusNum 属性
const computedFocusNum = computed(() => {
  return populationBaseList.value.map(item => ({
    ...item,
    focusNum: item.residentPopulationNum !== null && item.generalPopulationNum !== null
      ? item.residentPopulationNum - item.generalPopulationNum
      : 'N/A'
  }));
});

// 监听普通人群数值或常住人口数值的变化
watch([() => form.value.generalPopulationNum, () => form.value.residentPopulationNum], ([newGeneral, newResident], [oldGeneral, oldResident]) => {
  console.log('普通人群数值变化:', newGeneral, oldGeneral);
  console.log('常住人口数值变化:', newResident, oldResident);
});

// 方法：获取普通人群数值
const getGeneralPopulationValue = () => {
  console.log(form.value.generalPopulationNum);
};








/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  populationBaseFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: PopulationBaseVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加人口基数";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: PopulationBaseVO) => {
  reset();
  dialog.visible = true;
  dialog.title = "修改人口基数";
  Object.assign(form.value, row);


}

/** 提交按钮 */
const submitForm = () => {
  populationBaseFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updatePopulationBase(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addPopulationBase(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: PopulationBaseVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除人口基数编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delPopulationBase(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('basicPublic/populationBase/export', {
    ...queryParams.value
  }, `populationBase_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
